package pers.books.serviceImpl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import pers.books.dao.BookAuthorDao;
import pers.books.dao.BookDao;
import pers.books.dao.BookPressDao;
import pers.books.dao.BuyTypeDao;
import pers.books.dao.UserBookDao;
import pers.books.entity.Book;
import pers.books.entity.UserBook;
import pers.books.service.UserBookService;
import pers.books.util.ResultMessage;
import pers.books.util.StaticMessage;
import pers.books.util.UUID;

/**
 * 
 * UserBookServiceImpl
 *
 * @author 姜治昊
 * @time 2018年4月28日 下午2:43:44
 */
@Service
public class UserBookServiceImpl implements UserBookService{
	
	@Autowired
	private UserBookDao userBookDao;
	
	@Autowired
	private BookDao bookDao;
	
	@Autowired
	private BookAuthorDao bookAuthorDao;
	
	@Autowired
	private BookPressDao bookPressDao;
	
	@Autowired
	private BuyTypeDao buyTypeDao;
	
	

	@Override
	@Transactional(readOnly=true)
	public Map<String, Object> getBooks(String userId, String bookName, String isbn, String site, int page, int rows) {
		// TODO Auto-generated method stub
		Map<String, Object> result = new HashMap<>();
		try {
			List<UserBook> myBooks = userBookDao.getBooks(userId, bookName, isbn,  site, page, rows);
			int total  = userBookDao.getBooksCount(userId, bookName, isbn,  site);
			result.put("total", total);
			result.put("rows", myBooks);
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}

	/**
	 * 添加我的图书
	 */
	@Override
	@Transactional
	public ResultMessage<?> addMyBook(UserBook userBook) {
		Book book = userBook.getBook();
		if(null != book) {
			if(null == book.getId()) {
				book.setId(UUID.getUUID());
				int resultBookAdd = bookDao.addBook(book);
				String author = book.getAuthors();
				String presse = book.getPresses();
				String[] authors = author.split(",");
				int addBookAuthorResult = bookAuthorDao.addBookAuthors(book.getId(), authors);
				String[] presses = presse.split(",");
				int addBookPressResult = bookPressDao.addBookPresses(book.getId(), presses);
				if(resultBookAdd != 1 || addBookAuthorResult != authors.length || addBookPressResult != presses.length) {
					throw new RuntimeException(StaticMessage.ADD_BOOK_ERROR);
				}
			}
		} else {
			throw new RuntimeException(StaticMessage.HTTP_PARAMS_ERROR);
		}
		int result = userBookDao.addMyBook(userBook);
		if(result != 1) {
			throw new RuntimeException(StaticMessage.ADD_MY_BOOK_ERROR);
		}
		return ResultMessage.createSuccessResultMessage(StaticMessage.ADD_MY_BOOK_SUCCESS);
	}

}
